package com.example.demo.service;

import com.example.demo.dao.LoginUserMapper;
import com.example.demo.entity.CommonResult;
import com.example.demo.entity.loginUser;
import com.example.demo.utils.JwtUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginUseService implements LoginUserServiceimpl {
    @Autowired
    LoginUserMapper loginUserMapper;

    @Override
    public CommonResult login_authentication(String login_name, String password, String role) {
        List<loginUser> loginUsers = loginUserMapper.login_authentication(login_name, password,role);
        if(loginUsers.size()>=1){
            Map<String, String> map = new HashMap<String,String>();
            map.put("login_name",login_name);
            map.put("password",password);
            map.put("role",role);
            //生成令牌
            try {
                String token = JwtUtils.getToken(map);
                return new CommonResult(200,"登录成功",token);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
        return new CommonResult(401, "登录失败,密码或者用户名错误", login_name);

    }

    @Override
    public CommonResult GetOnepagesUser(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<loginUser> getalldUser = loginUserMapper.GetallUser();
        if (getalldUser.size() <= 0) {
            return new CommonResult(200, "暂时没有用户");
        }
        PageInfo pageInfo = new PageInfo(getalldUser);
        return new CommonResult(200, "用户第" + pageInfo.getPageNum() + "页获取成功", pageInfo);
    }

    @Override
    public CommonResult addUser(loginUser loginUser) {
        int i = loginUserMapper.addUser(loginUser);
        if(i>0){
            return new CommonResult(200, "添加成功", "用户名"+loginUser.getLogin_name());
        }
        return new CommonResult(401, "添加失败", "用户名"+loginUser.getLogin_name());
    }

    @Override
    public CommonResult updateUser(loginUser loginUser) {
        int i = loginUserMapper.updateUser(loginUser);
        if(i>0){
            return new CommonResult(200, "修改成功", "用户id"+loginUser.getId());
        }
        return new CommonResult(401, "修改失败", "用户id"+loginUser.getId());
    }

    @Override
    public CommonResult deleteUser(Integer id) {

        int i = loginUserMapper.deleteUser(id);
        if(i>0){
            return new CommonResult(200, "删除成功", "用户id"+id);
        }
        return new CommonResult(401, "删除失败", "用户id"+id);
    }

    @Override
    public CommonResult selectUser(Integer id, String login_name) {
        List<loginUser> selectdrug = loginUserMapper.selectUser(id,login_name);
        return new CommonResult(200,"用户信息",selectdrug);
    }
}
